﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CarlosAg.ExcelXmlWriter;
using Edge.Business.Domain.Application;
using Edge.Common;
using Edge.Common.ComponentModel.Parameters;
using Edge.Common.Mail;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.OAuth;
using Shop.Business.Domain.Catalog;
using Shop.Business.Domain.Catalog.Parameter;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Pricing;
using Shop.Business.Upload;
using Shop.Web.AppCode;
using Image = System.Drawing.Image;
using Parameter=Shop.Business.Domain.Catalog.Parameter.Parameter;

namespace Shop.Web
{
    public partial class test : ShopBasePage
    {
        [QueryParameter("code", IsRequired = false)]
        public string code;
        [QueryParameter("isFB", IsRequired = false)]
        public bool isFB = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            
            HandlePage();
            if (!IsPostBack)
            {
                DataBind();
            }
        }

        protected void HandlePage()
        {
            if (Locator.GetService<IContextObjects>().Get<CustomerHolder>() == null)
                AccessDeniedMessage();
            else
            {
                Customer cc = Locator.GetService<IContextObjects>().Get<CustomerHolder>().Object;
                switch (cc.Role)
                {
                    case CustomerRole.Buyer:
                        AccessDeniedMessage();
                        break;
                        //                case CustomerRole.Manager:
                        //                    btnDelete.Visible = false;
                        //                    break;
                    case CustomerRole.Admin:
                        break;
                    default:
                        break;

                }
            }
        }

        protected void DataBind()
        {
            ddlBrand.DataSource = Locator.GetService<IBrandManager>().FindAll();
            ddlBrand.DataTextField = "Name";
            ddlBrand.DataValueField = "Id";
            ddlBrand.DataBind();
            ddlBrand.Items.Insert(0, new ListItem("", ""));
        }

        protected void btn_onclick(object sender, EventArgs e)
        {
            UploadCatalog uploadCatalog = new UploadCatalog(fuImage.PostedFile,chbUpdate.Checked,Locator.GetService<IContextObjects>().Get<CustomerHolder>().Object);
            int discount = 0;
            try
            {
                discount = Convert.ToInt32(tbDiscount.Text);

            }
            catch
            {

            }
            if (!StringUtils.IsBlankOrNull(ddlBrand.SelectedValue))
            {
                Brand brand = Locator.GetService<IBrandManager>().Load(Convert.ToInt32(ddlBrand.SelectedValue));
                if (brand != null)
                {
                    if (brand.Name == "Амаэру")
                        uploadCatalog.UploadAmameru(brand);
                    else
                    {
                        uploadCatalog.Upload(brand.Name, discount);
                    }
                }
            }
            else
                uploadCatalog.Upload();
            
        }

        protected void btnInvisible_Click(object sender, EventArgs e)
        {
            if (!StringUtils.IsBlankOrNull(ddlBrand.SelectedValue))
            {
                Brand brand = Locator.GetService<IBrandManager>().Load(Convert.ToInt32(ddlBrand.SelectedValue));
                if (brand != null)
                    Locator.GetService<IProductManager>().SetVisibleFalse(brand);
            }
        }

        protected void btnEmail_OnClick(object sender, EventArgs e)
        {

            string to = tbEmail.Text;
            Dictionary<string, object> ret = new Dictionary<string, object>();
            ret["Test"] = "Check";
            string template = HttpContext.Current.Server.MapPath("txt") + "\\mail\\test_mail.txt";
            SendMailByTemplate mlInvite = new SendMailByTemplate("Test интернет-магазин Морлин", template, null, to, null, ret);
            mlInvite.Send();
        }

        protected void btnClearImage_Click(object sender, EventArgs e)
        {
            ltImgList.Text = "";
            string[] fileList = FileUtils.ImgList(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product\\");
            for (int i = 0; i < fileList.Length; i++)
            {
                if (fileList[i].Contains("IMG") && !fileList[i].Contains("thumb"))
                {
                    string str = fileList[i].Substring(fileList[i].IndexOf("IMG")+3, fileList[i].LastIndexOf(".") - fileList[i].IndexOf("IMG")-3);
                    
                    ProductGroup productGroup = Locator.GetService<IProductGroupManager>().Load(Convert.ToInt32(str));
                    try
                    {
                        Brand brand = productGroup.Brand;
                        Image original = Image.FromFile(fileList[i]);
                        if (original.Width < original.Height)
                        {
                            original.Dispose();
                            File.Move(fileList[i], HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/" + "tmp_" + "IMG" + str + ".jpg");
                            FileUtils.AddWidth(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/" + "tmp_" + "IMG" + str + ".jpg", fileList[i]);
                            File.Delete(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/" + "tmp_" + "IMG" + str + ".jpg");
                            FileUtils.GetThumbnail(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/", "IMG" + str + ".jpg", "thumb_", 175, 0);
                            ltImgList.Text = ltImgList.Text + "<br/>" + str + " resize";
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        if (File.Exists(fileList[i]))
                            File.Delete(fileList[i]);
                        if (File.Exists(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/thumb_IMG" + str + ".jpg"))
                            File.Delete(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/thumb_IMG" + str + ".jpg");
                        if (Directory.Exists(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/F" + str + "/"))
                        {
                            Directory.Delete(HttpContext.Current.Server.MapPath("../images") + "\\" + "Product/F" + str +"/",true);
                        }
                        ltImgList.Text = ltImgList.Text + "<br/>" + fileList[i] + " del";
                    }
                }
            }
        }

        protected void btnVKAuth_Click(object sender, EventArgs e)
        {
            

            //после возвращения к нам
           
        }
        protected void btnFBAuth_Click(object sender, EventArgs e)
        {
            OAuth2 facebook = new OAuth2("296841663712917", "4ff397794668cbedef8ec54da9568e3d", "https://www.facebook.com/dialog/oauth", "https://graph.facebook.com/oauth/access_token", "http://morlin.ru/admin/test.aspx?isFB=true");
            Session["facebook"] = facebook; //сохраняемся в сессии
            Response.Redirect(facebook.GetAuthCode());

            //после возвращения к нам

        }

    }
}
